package com.zerowidth.moc.web.common;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import static com.zerowidth.moc.web.common.SMSHelper.Const.LOGIN_SIGN_NAME;
import static com.zerowidth.moc.web.common.SMSHelper.Const.LOGIN_TEMPLATE_CODE;

public class SMSHelper {

    /**
     * 阿里云短信服务参数
     */
    private static String regionId = "cn-hangzhou";
    private static String accessKeyId = "LTAI4G8wWow68j8iTno9LWfk";
    private static String secret = "xtBbNMGLwL2K2BGGQodSg44eYEwUqs";

    public static class Const {
        public static final String LOGIN_SIGN_NAME = "宝宝小屋";
        public static final String LOGIN_TEMPLATE_CODE = "SMS_194910771";
    }

    /**
     * @param phone 手机号
     * @param code
     * @return
     */
    public static CommonResponse sendSMS_Login(String phone, String code) throws ServerException, ClientException {
        return sendSMS(phone, code, LOGIN_SIGN_NAME, LOGIN_TEMPLATE_CODE);
    }

    public static CommonResponse sendSMS(String phone, String code, String signName,
                                         String TemplateCode) throws ServerException, ClientException {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", TemplateCode);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        request.putQueryParameter("TemplateParam", jsonObject.toJSONString());
        request.putQueryParameter("OutId", "register");

        CommonResponse response = client.getCommonResponse(request);
        return response;
    }

}
